<template>
    <div class="my-articles-module">
        <h2>我的文章</h2>
        <el-button @click="goToCommunity">返回</el-button>
            <el-table :data="myArticles" style="width: 100%;">
                <el-table-column prop="title" label="文章标题" width="200"></el-table-column>
                <el-table-column prop="skimNum" label="浏览量" width="200"></el-table-column>
                <el-table-column prop="likesTotalNums" label="点赞量" width="200"></el-table-column>
                <el-table-column prop="userId" label="作者" width="200"></el-table-column>
                <el-table-column prop="createTime" label="发布时间" width="200"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button size="small" @click="openEditDialog(scope.row.id)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteArticle(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 编辑文章对话框 -->
            <el-dialog v-model="editDialogVisible" title="编辑文章" width="50%" :before-close="closeDialog">
                <el-form :model="editArticleForm" label-width="100px" style="max-width: 460px;">
                    <el-form-item label="标题">
                        <el-input v-model="editArticleForm.title" placeholder="请输入标题"></el-input>
                    </el-form-item>
                    <el-form-item label="内容">
                        <el-input type="textarea" v-model="editArticleForm.content" placeholder="请输入内容" rows="5"></el-input>
                    </el-form-item>
                    <el-form-item label="摘要">
                        <el-input v-model="editArticleForm.summary" placeholder="请输入摘要"></el-input>
                    </el-form-item>
                    <el-form-item label="图片">
                        <el-upload
                            v-model:file-list="fileList"
                            v-model:action="actionUrl"
                            name="file"
                            limit="1"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                        >
                            <el-button type="primary">点击上传</el-button>
                        </el-upload>
                        <img v-if="editArticleForm.imageUrl" :src="editArticleForm.imageUrl" alt="预览图" class="preview-image">
                    </el-form-item>
                </el-form>
                <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="saveEditedArticle">保存</el-button>
                </span>
                </template>
            </el-dialog>
    </div>
</template>


<script setup>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { ElMessage, ElDialog, ElButton, ElForm, ElFormItem, ElInput, ElUpload, ElTable, ElTableColumn } from 'element-plus';
import router from "@/router";
import qs from "qs";


axios.defaults.withCredentials = true; // 允许跨域请求携带凭据
// 获取当前用户信息
const user = JSON.parse(localStorage.getItem('user'));

const myArticles = ref([]);

// 编辑对话框相关
const editDialogVisible = ref(false);
// 编辑文章表单
const editArticleForm = ref({
    id: '',
    title: '',
    content: '',
    summary: '',
    imageUrl: ''
});

/**
 * 获取当前用户的文章
 */
const fetchMyArticles = () => {
    axios.get(BASE_URL + '/v1/article/selectMyArticle?userId='+user.id)
        .then((response) => {
            if (response.data.code === 2000) {
                myArticles.value = response.data.data;
            } else {
                ElMessage.error(response.data.msg);
            }
        });
};

/**
 * 打开编辑对话框
 */
const openEditDialog = (id) => {
  router.push('/createArticle?id='+id);
};


/**
 * 关闭弹窗的方法
 */
const closeDialog = () => {
    if (confirm('确认关闭吗？')) {
        editDialogVisible.value = false;
        editArticleForm.value = {};
    }
};

/**
 * 保存编辑的文章
 */
const saveEditedArticle = () => {
    let data = qs.stringify(editArticleForm.value);
    console.log(data);
    axios.post(BASE_URL + '/v1/article/insert', data)
        .then((response) => {
            if (response.data.code === 2000) {
                ElMessage.success('文章保存成功');
                editDialogVisible.value = false;
                fetchMyArticles();
            } else {
                ElMessage.error(response.data.msg);
            }
        });
};

/**
 * 删除文章
 */
const deleteArticle = (articleId) => {

    if (confirm('确认删除吗？')) {
        axios.post(BASE_URL + '/v1/article/delete?articleId='+articleId)
            .then((response) => {
                if (response.data.code === 2000) {
                    ElMessage.success('文章删除成功');
                    fetchMyArticles();
                } else {
                    ElMessage.error(response.data.msg);
                }
            });
    }
};

/**
 * 返回社区页面
 */
const goToCommunity = () => {
    router.push('/community');
};

/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
    //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
    let imgUrl = uploadFile.response.data;
    //2.给后端发请求,删除图片
    axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
        .then((response) => {
            if (response.data.code === 2000) {
                ElMessage.success('删除成功!');
            }
        });
};
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
    console.log(uploadFile);
};
//移除现有的图片
const removeExistingImage = () => {
    axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + editArticleForm.value.imageUrl)
        .then((response) => {
            if (response.data.code === 2000) {
                ElMessage.success('图片删除成功');
                editArticleForm.value.imageUrl = '';
                fileList.value = [];
            } else {
                ElMessage.error(response.data.msg);
            }
        });
};
/**图片上传相关代码结束**/

onMounted(() => {
    fetchMyArticles();
});
</script>


<style scoped>
.my-articles-module {
    padding: 20px;
}

.el-table {
    margin-top: 20px;
}

.el-table__header-wrapper th {
    background-color: #f5f7fa;
}

.el-table__body-wrapper td {
    text-align: center;
}


.preview-image {
    max-width: 100%;
    max-height: 100px;
    margin-top: 10px;
}
</style>
